<?php
namespace backend\modules\openapi\controllers;

use backend\controllers\BaseController;
use backend\models\OpenapiShop;
use common\extended\oss\Functions;
use common\models\SysShop;
use yii\data\Pagination;
use yii\helpers\Url;

/**
 * 线上店铺管理
 * @author     chenxiaolin
 * @date        2016年3月17日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class ShopController extends BaseController
{
    public $enableCsrfValidation = false;
    public function init(){
        parent::init();
        $this->layout = '/agent';
    }
    /**
     * 线上店铺详情(调用接口)
     * @date: 2016年3月17日 
     * @author: chenxiaolin
     */
    public function actionIndex()
    {
        //获取url
        $baseUrl = \Yii::$app->params['baseUrl'];
        $urlInfo = \Yii::$app->params['beautyinfo'];
        $urlEdit = \Yii::$app->params['editBeautyinfo'];
        $model = new OpenapiShop();
        //获取当前登录的分店ID
        $userInfo = $this->userInfo;
        $shop_id = $userInfo->shop_id;
        if(!$this->request->isPost){
            //查询是否开通线上店铺
            $shop = SysShop::find()->where("shop_id = :id",[':id' => $shop_id])->one();
            if($shop->isopen_online == 0){
                $this->error('开通线上店铺即可使用此功能！');
            }
            if($shop->isopen_online == 2){
                $this->error('审核通过即可使用此功能！');
            }
            //获取标签
            $tag = $this->actionTags();
            $data = json_encode(array('shop_id' => $shop_id));
            // 发送请求获取美容院详情
            try {
                $get_url_msg = $model->get_url_msg($data, $baseUrl.$urlInfo);
                $get_url_msg = json_decode($get_url_msg, true);
                if($get_url_msg['status'] != 10000){
                    $this->error('获取美容院信息失败！');
                }
                $bp_medal = $get_url_msg['result']['bp_medal'];
                $get_url_msg['result']['bp_medal'] = substr($bp_medal, 1,1);
                return $this->render('index', ['model' => $model, 'get_url_msg' => $get_url_msg['result'], 'tag' => $tag]);
            } catch (\Exception $e) {
                $this->error('访问网络出错！');
            }
            
        }
        // 表单数据上传
        if ($this->request->isPost) {
            //获取数据
            $post = $this->request->post();
            $bp_cover = $post['oldCover'];
            $bp_photos = [];
            $upload = new Functions();
            try {
                if(!empty($_FILES['bp_cover']['name'])){//封面不为空，上传封面
                    if ($_FILES['bp_cover']['error'] === 0) {
                        // 上传图片到图片服务器
                        $bp_cover = $upload->uploadDemo("bp_cover", 'bp-pic/' . date("Y", time()) . '/' . date("m", time()) . '/' . date("d", time()) . '/' . date("H", time()));
                    }
                }
                if(!empty($_FILES['bp_photos'])){//轮播图片
                    if ($_FILES['bp_photos']['error'][0] === 0) {
                        $bp_photos = $upload->uploadFiles('bp_photos', 'bp-pic/' . date("Y", time()) . '/' . date("m", time()) . '/' . date("d", time()) . '/' . date("H", time()));
                    }
                }
            } catch (\Exception $e) {
                $this->error('上传图片失败！');
            }
            
            //修改信息
            $arr = [
                'bp_id' => $post['bp_id'],
                'bp_name' => $post['bp_name'],
                'bp_cover' => $bp_cover,
                'bp_tel' => $post['bp_tel'],
                'bp_medal_verify' => $post['bp_medal'],
                'bp_tags' => $post['tag'],
                'bp_owner_mobile' => $post['bp_owner_mobile'],
                'bp_intro' => $post['bp_intro'],
                'low_price' => $post['low_price'],
                'open_year' => $post['open_year'],
                'shop_area' => $post['shop_area'],
                'service_num' => $post['service_num'],
                'time' => $post['business_time'],
                'facilities' => $post['facilities'],
                'pics' => $bp_photos,
                'shop_id' => $shop_id,
            ];
            $datas = json_encode($arr);
            // 发送请求修改信息
            try {
                $rs = $model->get_url_msg($datas, $baseUrl.$urlEdit);
                $rs = json_decode($rs, true);
                if($rs['status'] != 10000){
                    $this->error('修改美容院信息失败！');
                }
                $this->redirect(Url::toRoute('shop/index'));
            } catch (\Exception $e) {
                $this->error('访问网络出错！');
            }
        }
    }
    /**
     * 删除轮播图片
     * @date: 2016年3月19日 
     * @author: chenxiaolin
     */
    public function actionDeletephotos(){
        //获取url
        $baseUrl = \Yii::$app->params['baseUrl'];
        $delUrl = \Yii::$app->params['deletePhoto'];
        
        $pId = $this->request->post('pid');//图片Id
        $bId = $this->request->post('bid');//美容院Id
        //发送请求删除图片
        $model = new OpenapiShop();
        $data = [
            'pid' => $pId,
            'bid' => $bId,
        ];
        $data = json_encode($data);
        try {
            $result = $model->get_url_msg($data, $baseUrl.$delUrl);
            $result = json_decode($result, true);
            if ($result['status'] == 10000) {
                $arr = [
                    'status' => 10000,
                    'message' => '删除成功',
                ];
                return json_encode($arr);
            }else{
                $arr = [
                    'status' => 0,
                    'message' => '删除失败',
                ];
                return json_encode($arr);
            }
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
    }
    /**
     * 线上项目列表
     * @date: 2016年3月17日 
     * @author: chenxiaolin
     */
    public function actionServicelist(){
        $baseUrl = \Yii::$app->params['baseUrl'];
        $listUrl = \Yii::$app->params['servicelist'];
        //获取当前登录的分店ID
        $userInfo = $this->userInfo;
        $shop_id = $userInfo->shop_id;
        //查询是否开通线上店铺
        $shop = SysShop::find()->where("shop_id = :id",[':id' => $shop_id])->one();
        if($shop->isopen_online == 0){
            $this->error('开通线上店铺即可使用此功能！');
        }
        if($shop->isopen_online == 2){
            $this->error('审核通过即可使用此功能！');
        }
        //获取搜索条件
        $service_name = $this->request->get('service_name','');
        $type = intval($this->request->get('type',-10000));
        $arr = [
                'shop_id' => $shop['shop_id'],
                'type' => $type,
                'keyword' => $service_name,
            ];
        //访问接口，获得服务项目列表
        $model = new OpenapiShop();
        $data = json_encode($arr);
        // 发送请求获取数据
        try {
            $result = $model->get_url_msg($data, $baseUrl.$listUrl);
            $result = json_decode($result, true);
            $list = [];
            $pages = [];
            if ($result['status'] == 10000) {
                $list = $result['result'];
                $pages = new Pagination(['totalCount' => count($list),'pageSize' => 20]);
                $list = array_slice($list, $pages->offset,$pages->limit);
            }else{
                $this->error('获取数据失败，稍后再试！');
            }
            return $this->render('servicelist',[
                'service_name' => $service_name,
                'type' => $type,
                'data' => $list,
                'page' => $pages,
            ]);
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
        
    }
    /**
     * 添加服务项目
     * @date: 2016年3月19日 
     * @author: chenxiaolin
     */
    public function actionServiceadd()
    {
        $baseUrl = \Yii::$app->params['baseUrl'];
        $serviceUrl = \Yii::$app->params['service'];
        $userInfo = $this->userInfo;
        if(!$this->request->isPost){
            return $this->render('service');
        }
        if(empty($_FILES['service_cover']['name'])){
            $this->error('图片必须上传！');
        }
        $post = \Yii::$app->request->post();
        $path = '';
        try {
            if ($_FILES['service_cover']['error'] === 0) {
                // 上传图片到图片服务器
                $upload = new Functions();
                $path = $upload->uploadDemo('service_cover', 'bp-cover/' . date("Y", time()) . '/' . date("m", time()) . '/' . date("d", time()) . '/' . date("H", time()));
            }
        } catch (\Exception $e) {
            $this->error('上传图片失败！');
        }
        
        //访问接口，获得服务项目列表
        $model = new OpenapiShop();
        $arr = [
            'shop_id' => $userInfo->shop_id,
            'service_name' => $post['service_name'],
            'service_cover' => $path,
            'service_price' => $post['service_price'],
            'service_unit' => $post['service_unit'],
            'is_shell' => $post['service_is_sell'],
            'content' => $post['service_intro'],
            'service_id' => ''
        ];
        $data = json_encode($arr);
        // 发送请求添加数据
        try {
            $result = $model->get_url_msg($data, $baseUrl.$serviceUrl);
            $result = json_decode($result, true);
            if ($result['status'] != 10000) {
                $this->error('添加失败！');
            }
            $this->redirect(Url::toRoute(['shop/servicelist']));
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
    }
    /**
     * 修改服务项目
     * @date: 2016年3月19日
     * @author: chenxiaolin
     */
    public function actionServiceedit(){
        $baseUrl = \Yii::$app->params['baseUrl'];
        $serviceUrl = \Yii::$app->params['service'];
        $serviceInfo = \Yii::$app->params['serviceInfo'];
        $userInfo = $this->userInfo;
        $model = new OpenapiShop();
        if(!$this->request->isPost){
            $id = intval($this->request->get('id',0));
            if($id < 1){
                $this->error('参数错误');
            }
            //数据验证
            $arr = [
                'id' => $id,
                'shop_id' => $userInfo->shop_id
            ];
            $data = json_encode($arr);
            //发送请求，获取服务项目详情
            try {
                $result = $model->get_url_msg($data, $baseUrl.$serviceInfo);
                $result = json_decode($result, true);
                if($result['status'] == 10000){
                    if(empty($result['result'])){
                        $this->error('项目不存在！');
                    }
                    return $this->render('service',['data' => $result['result']]);
                }else{
                    $this->error('获取服务项目详情失败！');
                }
            } catch (\Exception $e) {
                $this->error('访问网络出错！');
            }
        }
        //获取数据
        $post = $this->request->post();
        $oldCover = $post['old_cover'];
        try {
            if(!empty($_FILES['service_cover']['name'])){
                if ($_FILES['service_cover']['error'] === 0) {
                    // 上传图片到图片服务器
                    $upload = new Functions();
                    $oldCover = $upload->uploadDemo('service_cover', 'bp-cover/' . date("Y", time()) . '/' . date("m", time()) . '/' . date("d", time()) . '/' . date("H", time()));
                }
            }
        } catch (\Exception $e) {
            $this->error('上传图片失败！');
        }
        $arrs = [
            'shop_id' => $userInfo->shop_id,
            'service_name' => $post['service_name'],
            'service_cover' => $oldCover,
            'service_price' => $post['service_price'],
            'service_unit' => $post['service_unit'],
            'is_shell' => $post['service_is_sell'],
            'content' => $post['service_intro'],
            'service_id' => $post['id']
        ];
        $datas = json_encode($arrs);
        // 发送请求修改数据
        try {
            $result = $model->get_url_msg($datas, $baseUrl.$serviceUrl);
            $result = json_decode($result, true);
            if ($result['status'] != 10000) {
                $this->error('修改失败！');
            }
            $this->redirect(Url::toRoute(['shop/servicelist']));
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
    }
    /**
     * 修改服务项目状态（上架、下架）
     * @date: 2016年3月19日
     * @author: chenxiaolin
     */
    public function actionSetstate(){
        $baseUrl = \Yii::$app->params['baseUrl'];
        $serviceUrl = \Yii::$app->params['service'];
        $userInfo = $this->userInfo;
        $model = new OpenapiShop();
        //获取数据 
        $id = intval($this->request->get('id'),0);
        $is_sell = intval($this->request->get('is_sell'),0);
        if($id < 1 || !in_array($is_sell, [1,-1])){
            $this->error('参数错误！');
        }
        $arr = [
            'shop_id' => $userInfo->shop_id,
            'is_shell' => $is_sell,
            'service_id' => $id
        ];
        $data = json_encode($arr);
        // 发送请求修改状态
        try {
            $result = $model->get_url_msg($data, $baseUrl.$serviceUrl);
            $result = json_decode($result, true);
            if ($result['status'] != 10000) {
                $this->error('修改失败！');
            }
            $this->redirect(Url::toRoute(['shop/servicelist']));
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
    }
    /**
     * 获取美容院标签
     * @date: 2016年3月17日 
     * @author: chenxiaolin
     */
    public function actionTags()
    {
        $baseUrl = \Yii::$app->params['baseUrl'];
        $tagUrl = \Yii::$app->params['tag'];
        $model = new OpenapiShop();
        // 发送请求获取数据
        try {
            $get_url_msg = $model->get_url_msg('', $baseUrl.$tagUrl);
            $get_url_msg = json_decode($get_url_msg, true);
            
            if ($get_url_msg['status'] != 10000) {
                $this->error('访问网络出错！');
            }
            return $get_url_msg;
        } catch (\Exception $e) {
            $this->error('访问网络出错！');
        }
    }
}
